package cn.nfwx.tv.controller;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseFragment;
import cn.nfwx.tv.callback.ResponseCallback;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.callback.UserCallBack;
import cn.nfwx.tv.conts.Constants;
import cn.nfwx.tv.events.ToMineItemEvent;
import cn.nfwx.tv.fragment.SettingFragment;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.EditNullFilter;
import cn.nfwx.tv.helper.UmengPushHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.UserManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.User;
import cn.nfwx.tv.model.UserModel;
import cn.nfwx.tv.okhttp.UrlHelper;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.DensityUtil;
import cn.nfwx.tv.util.DialogUtil;
import cn.nfwx.tv.util.FileUtil;
import cn.nfwx.tv.util.GlideCacheUtil;
import cn.nfwx.tv.util.MD5Util;
import cn.nfwx.tv.util.NetworkUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.util.ToolUtil;
import cn.nfwx.tv.util.ZXingUtils;
import cn.nfwx.tv.vo.ResultErrorVo;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by dell on 2017/12/13.
 */

public class SettingViewController implements View.OnClickListener {
    private AppCompatActivity activity;
    private BaseFragment mFragment;
    private RelativeLayout setting_change_pw, setting_clear_cache, setting_share_friends, setting_about_us, setting_to_use, setting_play_msg;
    private EditText setting_edit_phone, setting_edit_smscode, setting_edit_pw;
    private TextView setting_btn_code, setting_btn_commit, btn_cache_cancle, btn_cache_sure, cache_num;
    private int countDown = 60;
    private static final int MSG_COUNT_LOGIN = 1;//短信验证码
    private Dialog changePwDialog, cacheDialog, shareDialog, aboutDialog;
    private ImageView share_to_friend, share_to_wechat;
    private CheckBox push_checkbox, play_checkbox;
    private KProgressHUD progress;
    private boolean hasPhone = true;

    public SettingViewController(AppCompatActivity activity, SettingFragment fragment, View view) {
        this.activity = activity;
        mFragment = fragment;
        initView(view);
    }

    public void initView(View view) {
        play_checkbox = view.findViewById(R.id.play_checkbox);
        push_checkbox = view.findViewById(R.id.push_checkbox);
        setting_to_use = view.findViewById(R.id.setting_to_use);
        setting_change_pw = view.findViewById(R.id.setting_change_pw);
        setting_clear_cache = view.findViewById(R.id.setting_clear_cache);
        setting_share_friends = view.findViewById(R.id.setting_share_friends);
        setting_about_us = view.findViewById(R.id.setting_about_us);
        setting_play_msg = view.findViewById(R.id.setting_play_msg);
        cache_num = view.findViewById(R.id.cache_num);
        setting_change_pw.setOnClickListener(this);
        setting_clear_cache.setOnClickListener(this);
        setting_share_friends.setOnClickListener(this);
        setting_about_us.setOnClickListener(this);
        setting_to_use.setOnClickListener(this);
        setting_play_msg.setOnClickListener(this);
        loadFileSize();
        push_checkbox.setChecked(SharePrefUtil.getPushChoose(activity));
        push_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                SharePrefUtil.savePushChoose(activity, b);
                if (b) {
                    UmengPushHelper.getInstance().open();
                } else {
                    UmengPushHelper.getInstance().close();
                }
            }
        });
        play_checkbox.setChecked(SharePrefUtil.getDownloadChoose(activity));
        play_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked && NetworkUtil.getNetworkType(activity) != 1) {
//                    NFWXApplication.getInstance().getP2PSMgr().allowDownload(1, true);
                } else {
//                    NFWXApplication.getInstance().getP2PSMgr().allowDownload(2, true);
                }
            }
        });
    }

    private void loadFileSize() {
        Observable.create(new ObservableOnSubscribe<Long>() {
            @Override
            public void subscribe(ObservableEmitter<Long> e) {
                long photoSize = GlideCacheUtil.getInstance().getCacheSize(activity);
//                File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
//                        Environment.DIRECTORY_PICTURES), activity.getString(R.string.app_name));
//                long videoSize = FileUtil.getFileSize(mediaStorageDir);
//                File fileDir = new File(activity.getFilesDir(), "movie");
//                long videoSize2 = FileUtil.getFileSize(fileDir);
                e.onNext(photoSize);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mFragment.<Long>bindToLifecycle())
                .subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long s) {
                cache_num.setText(FileUtil.getFormatSize(s));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_change_pw:
                if (!AccountHelper.getInstance().isLogin(activity)) {
                    Toast.makeText(activity, "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                changePwDialog = new Dialog(activity, R.style.MyDialog);
                View dialogView = View.inflate(activity, R.layout.dialog_change_pw, null);
                setting_edit_phone = dialogView.findViewById(R.id.setting_edit_phone);
                ToolUtil.toCheckPhone(activity, setting_edit_phone, 1, new ValueCallback<Boolean>() {
                    @Override
                    public void onReceiveValue(Boolean value) {
                        hasPhone = value;
                    }
                });
                setting_btn_code = dialogView.findViewById(R.id.setting_btn_code);
                setting_edit_smscode = dialogView.findViewById(R.id.setting_edit_smscode);
                setting_edit_pw = dialogView.findViewById(R.id.setting_edit_pw);
                setting_btn_commit = dialogView.findViewById(R.id.setting_btn_commit);
                setting_btn_code.setOnClickListener(this);
                setting_btn_commit.setOnClickListener(this);
                setting_edit_phone.setText(AccountHelper.getInstance().getPhone(activity));
                setting_edit_phone.setFilters(new InputFilter[]{new EditNullFilter()});
                setting_edit_smscode.setFilters(new InputFilter[]{new EditNullFilter(), new InputFilter.LengthFilter(6)});
                setting_edit_pw.setFilters(new InputFilter[]{new EditNullFilter(), new InputFilter.LengthFilter(15)});
                changePwDialog.setContentView(dialogView);
                Window dialogWindow = changePwDialog.getWindow();
                WindowManager m = activity.getWindowManager();
                Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
                WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
                p.width = (int) (d.getWidth() * 0.6); // 宽度设置为屏幕的0.65，根据实际情况调整
                dialogWindow.setAttributes(p);
                changePwDialog.show();
                changePwDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        setting_btn_code.setClickable(true);

                    }
                });
                break;
            case R.id.setting_clear_cache:
                View cacheView = View.inflate(activity, R.layout.dialog_clear_cache, null);
                btn_cache_cancle = cacheView.findViewById(R.id.btn_cache_cancle);
                btn_cache_sure = cacheView.findViewById(R.id.btn_cache_sure);
                btn_cache_cancle.setOnClickListener(this);
                btn_cache_sure.setOnClickListener(this);
                cacheDialog = getDialog(cacheView);
                cacheDialog.show();
                break;
            case R.id.setting_share_friends:
                View shareView = View.inflate(activity, R.layout.dialog_share_friend, null);
                share_to_friend = shareView.findViewById(R.id.share_to_friend);
                share_to_wechat = shareView.findViewById(R.id.share_to_wechat);
                ImageView iv_share = shareView.findViewById(R.id.iv_share);
                int width = DensityUtil.dip2px(activity, 120);
                Bitmap bitmap = ZXingUtils.createQRImage(UrlHelper.getAppqrcode(), width, width);
                iv_share.setImageBitmap(bitmap);
                share_to_friend.setOnClickListener(this);
                share_to_wechat.setOnClickListener(this);
                shareDialog = getDialog(shareView);
                shareDialog.show();
                break;
            case R.id.setting_about_us:
                final View aboutView = View.inflate(activity, R.layout.dialog_about_us, null);
                TextView version_code = aboutView.findViewById(R.id.version_code);
                version_code.setText("V" + AppUtil.getCrrentName(activity));
                aboutDialog = getDialog(aboutView);
                aboutDialog.show();
                break;
            case R.id.setting_btn_code://修改密码的获取验证码
                String smsMobileNo = setting_edit_phone.getText().toString().trim();
                if (TextUtils.isEmpty(smsMobileNo)) {
                    Toast.makeText(activity, R.string.toast_phone, Toast.LENGTH_LONG).show();
                    return;
                }
                if (!ToolUtil.isPhoneLegal(smsMobileNo)) {
                    Toast.makeText(activity, R.string.toast_right_phone, Toast.LENGTH_LONG).show();
                    return;
                }
                setting_btn_code.setClickable(false);//防止重复点击Button，否则多次点击button：每隔一秒发送消息多次执行
                if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_P2P) {
                    UserManager.requestSmsCode(activity, smsMobileNo, "bind", new ResponseWithFailListener<JSONObject>() {
                        @Override
                        public void onResponse(String tag, final JSONObject response) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    handler.sendEmptyMessage(MSG_COUNT_LOGIN);
                                    Toast.makeText(activity, "短信已发送", Toast.LENGTH_LONG).show();
                                    setting_btn_code.setClickable(true);
                                }
                            });

                        }

                        @Override
                        public void onFail(String requestTag, final String response) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Gson gson = new Gson();
                                        ResultErrorVo resultErrorVo = gson.fromJson(response, ResultErrorVo.class);
                                        setting_btn_code.setClickable(true);

                                        Toast.makeText(activity, "null".equals(resultErrorVo.getMsg()) ? "短信验证码发送失败" : resultErrorVo.getMsg(), Toast.LENGTH_LONG).show();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }
                            });
                        }

                        @Override
                        public void onError(String tag, Throwable t) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(activity, "验证码发送失败", Toast.LENGTH_LONG).show();
                                    setting_btn_code.setClickable(true);
                                }
                            });


                        }


                        @Override
                        public void onFinish() {

                        }
                    });
                } else if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_QPOP) {
                    if (!hasPhone) {
                        ToastUtil.show(activity, "该号码未注册");
                        return;
                    }
                    UserManager.requestIjkSmsCode(activity, smsMobileNo, new ResponseCallback<Integer>() {
                        @Override
                        public void onSuccess(String requestTag, final Integer response) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setting_btn_code.setClickable(true);
                                    if (response > 0) {
                                        handler.sendEmptyMessage(MSG_COUNT_LOGIN);
                                        Toast.makeText(activity, "短信已发送", Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        }

                        @Override
                        public void onFailure(String requestTag, String message) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setting_btn_code.setClickable(true);
                                }
                            });
                        }
                    });
                }
                break;
            case R.id.setting_btn_commit://修改密码的提交
                String mobile = setting_edit_phone.getText().toString().trim();
                if (TextUtils.isEmpty(mobile)) {
                    Toast.makeText(activity, "请输入手机号码", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!ToolUtil.isPhoneLegal(mobile)) {
                    Toast.makeText(activity, "请输⼊正确的手机号码", Toast.LENGTH_LONG).show();
                    return;
                }
                String smsCode = setting_edit_smscode.getText().toString().trim();
                if (TextUtils.isEmpty(smsCode)) {
                    Toast.makeText(activity, "请输入验证码", Toast.LENGTH_LONG).show();
                    return;
                }
                if (smsCode.length() != 6) {
                    Toast.makeText(activity, "验证码长度为6位", Toast.LENGTH_LONG).show();
                    return;
                }

                String pw = setting_edit_pw.getText().toString().trim();

                if (TextUtils.isEmpty(pw)) {
                    Toast.makeText(activity, "请输入密码", Toast.LENGTH_LONG).show();
                    return;
                }
                if (pw.length() < 6 || pw.length() > 15) {
                    Toast.makeText(activity, "密码长度为6-15位", Toast.LENGTH_LONG).show();
                    return;
                }

                progress = KProgressHUD.create(activity)
                        .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
//                        .setLabel("加载中")
//                        .setDetailsLabel("Downloading data")
                        .setCancellable(true)
                        .setAnimationSpeed(2)
                        .setDimAmount(0.5f);
                progress.show();
                if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_P2P) {

                    UserManager.bindPhone(activity, mobile, smsCode, pw, SharePrefUtil.getUser(activity).getAccess_token(), new UserCallBack() {
                                @Override
                                public void onSuccess(UserModel userModel) {
                                    SharePrefUtil.saveUser(activity.getApplicationContext(), userModel);//缓存用户数据
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progress.dismiss();
                                            changePwDialog.dismiss();
                                            Toast.makeText(activity, "密码修改成功", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                                @Override
                                public void onFail(String code, final String response) {
                                    Log.d("onFail", response);
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progress.dismiss();
                                            Toast.makeText(activity, R.string.toast_sms_error, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                                @Override
                                public void onError(String tag, Throwable t) {
                                    super.onError(tag, t);
                                    Log.d("onError", t.getMessage());
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progress.dismiss();
                                            Toast.makeText(activity, R.string.toast_sms_error, Toast.LENGTH_SHORT).show();
                                            changePwDialog.dismiss();
                                        }
                                    });
                                }

                                @Override
                                public void onComplete() {
                                    super.onComplete();
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progress.dismiss();
                                            changePwDialog.dismiss();
                                        }
                                    });
                                }
                            }

                    );
                } else if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_QPOP) {
                    if (!hasPhone) {
                        Toast.makeText(activity, "该号码未注册", Toast.LENGTH_LONG).show();
                        return;
                    }
                    UserManager.requestIjkResetPwd(activity, mobile, MD5Util.MD5(pw), smsCode, new ResponseListener<String>() {
                        @Override
                        public void onResponse(String requestTag, final String response) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();

                                    Result<User> result = JSON.parseObject(response, new TypeReference<Result<User>>() {
                                    }.getType());
                                    if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                                        if (result.getData() != null && result.getData().getUid() > 0) {
                                            changePwDialog.dismiss();
                                            ToastUtil.show(activity, "修改成功");
                                            AccountHelper.getInstance().saveUser(activity, result.getData());
                                            EventBus.getDefault().post(new ToMineItemEvent(MineFragment.POSITION_SUBSCRIPT));
                                        } else {
                                            ToastUtil.show(activity, "修改失败");
                                        }
                                    } else {
                                        ToastUtil.show(activity, result.getMessage());
                                    }
                                }
                            });
                        }

                        @Override
                        public void onError(String requestTag, Throwable t) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    ToastUtil.show(activity, "修改失败");
                                }
                            });
                        }

                        @Override
                        public void onFinish() {

                        }
                    });
                }
                break;
            case R.id.setting_to_use:
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), PlayerIntroductionController.newInstance(true));
                break;
            case R.id.btn_cache_cancle:
                cacheDialog.dismiss();
                break;
            case R.id.btn_cache_sure:
                GlideCacheUtil.getInstance().clearImageAllCache(activity);
                cacheDialog.dismiss();
                loadFileSize();
                break;
            case R.id.share_to_friend:
                share(SendMessageToWX.Req.WXSceneTimeline);
                break;
            case R.id.share_to_wechat:
                share(SendMessageToWX.Req.WXSceneSession);
                break;
            case R.id.setting_play_msg:
                if (!play_checkbox.isChecked()) {
                    View dialog_setting_net = View.inflate(activity, R.layout.dialog_setting_net, null);
                    TextView netCancle = dialog_setting_net.findViewById(R.id.btn_cancle);
                    TextView netSure = dialog_setting_net.findViewById(R.id.btn_sure);
                    final Dialog dialogNetDialog = DialogUtil.getDialog(activity, dialog_setting_net, false);
                    dialogNetDialog.show();
                    netCancle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialogNetDialog.cancel();
                        }
                    });
                    netSure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialogNetDialog.cancel();
                            SharePrefUtil.saveDownloadChoose(activity, true);
                            play_checkbox.setChecked(true);
//                            NFWXApplication.getInstance().getP2PSMgr().allowDownload(2, true);
                        }
                    });
                } else {
                    play_checkbox.setChecked(false);
                    SharePrefUtil.saveDownloadChoose(activity, false);
                    DownloadM3u8Controller.getInstance().pauseAll(activity);
//                    NFWXApplication.getInstance().getP2PSMgr().allowDownload(1, true);
                }


                break;

        }
    }

    public void share(int scene) {
        String title = "手机看电视新姿势，南方无线电视邀您一起炫！";
        String des = "看电视直播不卡顿，不延时，还不要钱，你不下，我下了！";
        Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);
        AppUtil.shareWebPage2WeiXin(activity, scene, UrlHelper.getAppLink(), title, des, bitmap);
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_COUNT_LOGIN:
                    if (countDown >= 0) {
                        setting_btn_code.setText(countDown-- + "s");
                        handler.sendEmptyMessageDelayed(MSG_COUNT_LOGIN, 1000);
                    } else {
                        setting_btn_code.setClickable(true);
                        countDown = 60;//复位，60s倒计时完后可以继续倒计时
                        setting_btn_code.setText("获取验证码");
                    }
                    break;

            }

        }
    };

    public Dialog getDialog(View view) {
        Dialog dialog = new Dialog(activity, R.style.MyDialog);
        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        WindowManager m = activity.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.8); // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.6); // 宽度设置为屏幕的0.65，根据实际情况调整
        dialogWindow.setAttributes(p);
        return dialog;
    }

}
